package com.learn.mvc;

import com.learn.mvc.service.HelloService;
import com.learn.mvc.service.UserService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

import javax.annotation.Resource;

@SpringBootApplication
public class MvcApplication implements CommandLineRunner {
    @Resource
    private HelloService helloService;

    /**
     * 无法使用 HelloService 这种方法，因为在main中是static方法，
     * Resource annotation is not supported on static fields
     * 当使用了 @Autowired 注入到main内部，在main调用执行时，service还没完成注入
     * Autowired
     * private UserService. userService.;

     * 使用 @Autowired 加static定义的 userService，在main方法调用时，还没完成创建无法读取到service数据
     * 此时调用内部方法会出现空指针异常
     * Exception in thread "main" java.lang.NullPointerException
     */
    public static void main(String[] args) {

        System.out.println("begin create");
        // 获取容器对象
        ConfigurableApplicationContext ctx = SpringApplication.run(MvcApplication.class, args);
        UserService userService = (UserService) ctx.getBean("userService");

        userService.sayHello("测试容器的service");
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("Runner");
        try {
            helloService.sayHello("mvc");
        } catch (Exception e) {
            throw new Exception(e);
        }

        System.out.println("Runner end");
    }
}
